package com.fieldchain.ex.fa100.utils.net.modle;

import com.fieldchain.ex.fa100.bean.event.BaseEvent;
import com.fieldchain.ex.fa100.utils.net.inter.BaseRequest;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by biyunlong
 * Email: 1225198434@qq.com
 * Data:  2018/9/4
 */
public abstract class ListRequest<T> extends BaseRequest {
    private int code=0;
    private String msg;
    @Override
    public void baseOnSucess(String jsonstr,String tags) {
        try {
            JSONObject jsonRoot = new JSONObject(jsonstr);
            code=jsonRoot.getInt("code");
            msg=jsonRoot.getString("msg");
            EventBus.getDefault().post(new BaseEvent(code,tags));
            List<T>list=new ArrayList<>();
            if(code==200) {
                JSONArray aar = jsonRoot.getJSONArray("data");
                Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
                for(int i=0;i<aar.length();i++){
                    JSONObject object=aar.getJSONObject(i);
                    T t=new Gson().fromJson(object.toString(),tClass);
                    list.add(t);
                }
                onSucess(list, code, msg);
            }else {
                onSucess(new ArrayList<T>(), code, msg);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void baseOnFaild(Exception e,String tags) {
        EventBus.getDefault().post(new BaseEvent(code,tags));
        onFaild(e);
    }

    public abstract void onSucess(List<T> list, int code, String msg);
    public abstract void onFaild(Exception e);
}
